<?php
// The source code packaged with this file is Free Software, Copyright (C) 2005 by
// Ricardo Galli <gallir at uib dot es>.
// It's licensed under the AFFERO GENERAL PUBLIC LICENSE unless stated otherwise.
// You can get copies of the licenses here:
// 		http://www.affero.org/oagpl.html
// AFFERO GENERAL PUBLIC LICENSE is also included in the file called "COPYING".

include_once('Smarty.class.php');
$main_smarty = new Smarty;

include('config.php');
include(mnminclude.'html1.php');
include(mnminclude.'ts.php');
include(mnminclude.'link.php');
include(mnminclude.'tags.php');
include(mnminclude.'user.php');
include(mnminclude.'csrf.php');
include(mnminclude.'smartyvariables.php');

// sessions used to prevent CSRF
	$CSRF = new csrf();

// sidebar
$main_smarty = do_sidebar($main_smarty);

// If not logged in, redirect to the index page
if ($current_user->user_id > 0 && $current_user->authenticated) {
		$login=$current_user->user_login;
} else {
		header('Location: ./');
		die;
}

// breadcrumbs and page title
$navwhere['text1'] = $main_smarty->get_config_vars('PLIGG_Visual_Breadcrumb_Profile');
$navwhere['link1'] = getmyurl('user2', $login, 'profile');
$navwhere['text2'] = $login;
$navwhere['link2'] = getmyurl('user2', $login, 'profile');
$navwhere['text3'] = $main_smarty->get_config_vars('PLIGG_Visual_Profile_ModifyProfile');
$navwhere['link3'] = getmyurl('profile', '');
$main_smarty->assign('navbar_where', $navwhere);
$main_smarty->assign('posttitle', " / " . $main_smarty->get_config_vars('PLIGG_Visual_Profile_ModifyProfile'));

// read the users information from the database
$user=new User();
$user->username = $login;
if(!$user->read()) {
	echo "invalid user";
	die;
}

// uploading avatar
if($_POST["avatar"] == "uploaded" && Enable_User_Upload_Avatar){
        upload_avatar();
}

// display profile
show_profile();

function upload_avatar() {
        global $CSRF;
        global $current_user;

        if (! $CSRF->check_valid($_POST['token'], 'profile_change')){
                echo 'There was a token error.<br>';
                return;
        }

        switch ($_FILES['image_file']['type']) {
        case 'image/jpeg':
        case 'image/pjpeg':
                $suffix = 'jpg';
                break;
        case 'image/png':
        case 'image/x-png':
                $suffix = 'png';
                break;
        case 'image/gif':
                $suffix = 'gif';
                break;
        default:
                echo 'Only these file types are allowed : jpeg, gif, png<br>';
                return;
        }

        $login = $current_user->user_login;

        // sanity check
        if (empty($login) || preg_match('{[_./:]}', $login)) {
                echo 'There is a problem with your username.<br>';
                return;
        }

        $prefix = "avatars/user_uploaded/" . $login;
        $trash = "avatars/user_uploaded/" . "_trash/";

        // remove old avatars.
        foreach (glob($prefix . "_*") as $file) {
                if (! @rename($file, $trash . basename($file))) {
                        @unlink($file);
                }
        }

        $tmpfile = $_FILES['image_file']['tmp_name'];
        $newimage = $prefix . "_original." . $suffix;
        if (! @move_uploaded_file($tmpfile, $newimage)) {
                echo 'There was an error moving the uploaded file.<br>';
                return;
        }
        chmod($newimage, 0644);

        resize_avatar($newimage, Avatar_Large);
        resize_avatar($newimage, Avatar_Small);
}

function show_profile() {
	global $user, $main_smarty, $the_template, $CSRF;


	if(isset($_POST['email'])){
		$savemsg = save_profile();
		$main_smarty->assign('savemsg', $savemsg);
	}

	$CSRF->create('profile_change', true, true);

	// assign avatar source to smarty
	$main_smarty->assign('UseAvatars', do_we_use_avatars());
	$main_smarty->assign('Avatar_ImgLarge', get_avatar('large', $user->avatar_source, $user->username, $user->email));
	$main_smarty->assign('Avatar_ImgSmall', get_avatar('small', $user->avatar_source, $user->username, $user->email));

	// module system hook
	$vars = '';
	check_actions('profile_show', $vars);
	
	// assign profile information to smarty
	$main_smarty->assign('user_id', $user->id);
	$main_smarty->assign('user_email', $user->email);
	$main_smarty->assign('user_login', $user->username);
	$main_smarty->assign('user_names', $user->names);
	$main_smarty->assign('user_username', $user->username);
	$main_smarty->assign('user_url', $user->url);
	$main_smarty->assign('user_publicemail', $user->public_email);
	$main_smarty->assign('user_location', $user->location);
	$main_smarty->assign('user_occupation', $user->occupation);
	$main_smarty->assign('user_aim', $user->aim);
	$main_smarty->assign('user_msn', $user->msn);
	$main_smarty->assign('user_yahoo', $user->yahoo);
	$main_smarty->assign('user_gtalk', $user->gtalk);
	$main_smarty->assign('user_skype', $user->skype);
	$main_smarty->assign('user_irc', $user->irc);
	$main_smarty->assign('user_karma', $user->karma);
	$main_smarty->assign('user_joined', get_date($user->date));
	$main_smarty->assign('user_avatar_source', $user->avatar_source);
	$user->all_stats();
	$main_smarty->assign('user_total_links', $user->total_links);
	$main_smarty->assign('user_published_links', $user->published_links);
	$main_smarty->assign('user_total_comments', $user->total_comments);
	$main_smarty->assign('user_total_votes', $user->total_votes);
	$main_smarty->assign('user_published_votes', $user->published_votes);
		
	// pagename	
	define('pagename', 'profile'); 
	$main_smarty->assign('pagename', pagename);
	
	$main_smarty->assign('form_action', $_SERVER["PHP_SELF"]);

	// show the template
	$main_smarty->assign('tpl_center', $the_template . '/profile_center');
	$main_smarty->display($the_template . '/pligg.tpl');	
}

function cleanit($value){
	$value = strip_tags($value);
	$value = trim($value);
	return $value;
}

function save_profile() {
	global $user, $current_user, $db, $main_smarty, $CSRF;

	if ($CSRF->check_valid($_POST['token'], 'profile_change')){
	
		if(!isset($_POST['save_profile']) || !isset($_POST['process']) || $_POST['user_id'] != $current_user->user_id ) return;
		if(!check_email(cleanit($_POST['email']))) {
			$savemsg = $main_smarty->get_config_vars("PLIGG_Visual_Profile_BadEmail");
			return $savemsg;
		} 
		else {
			$user->email=cleanit($_POST['email']);
		}

		$user->url=cleanit($_POST['url']);
		$user->public_email=cleanit($_POST['public_email']);
		$user->location=cleanit($_POST['location']);
		$user->occupation=cleanit($_POST['occupation']);
		$user->aim=cleanit($_POST['aim']);
		$user->msn=cleanit($_POST['msn']);
		$user->yahoo=cleanit($_POST['yahoo']);
		$user->gtalk=cleanit($_POST['gtalk']);
		$user->skype=cleanit($_POST['skype']);
		$user->irc=cleanit($_POST['irc']);
		$user->names=cleanit($_POST['names']);
	
		// module system hook
		$vars = '';
		check_actions('profile_save', $vars);
	
		$avatar_source = cleanit($_POST['avatarsource']);
		if($avatar_source != "" && $avatar_source != "useruploaded"){
			loghack('Updating profile, avatar source is not one of the list options.', 'username: ' . $_POST["username"].'|email: '.$_POST["email"]);
			$avatar_source == "";
		}
		$user->avatar_source=$avatar_source;
	
		if(!empty($_POST['newpassword']) || !empty($_POST['newpassword2'])) {
			$oldpass = $_POST['oldpassword'];
			$userX=$db->get_row("SELECT user_id, user_pass, user_login FROM " . table_users . " WHERE user_login = '".$user->username."'");
			$saltedpass=generateHash($oldpass, substr($userX->user_pass, 0, SALT_LENGTH));
			if($userX->user_pass == $saltedpass){
				if($_POST['newpassword'] !== $_POST['newpassword2']) {
					$savemsg = $main_smarty->get_config_vars("PLIGG_Visual_Profile_BadPass");
					return $savemsg;
				} else {
					$saltedpass=generateHash($_POST['newpassword']);
					$user->pass = $saltedpass;
					$user->store();
					$savemsg = $main_smarty->get_config_vars("PLIGG_Visual_Profile_PassUpdated");
					return $savemsg;
				}
			} else {
				$savemsg = $main_smarty->get_config_vars("PLIGG_Visual_Profile_BadOldPass");
				return $savemsg;
			}
		}
		$user->store();
		$user->read();
		$current_user->Authenticate($user->username, $user->pass);
		if(!$savemsg){$savemsg = $main_smarty->get_config_vars("PLIGG_Visual_Profile_DataUpdated");}
		return $savemsg;
	} else {
		return 'There was a token error.';
	}
}

?>
